<script setup>
import { ref, computed, watch } from 'vue';
import {
  ElTabs,
  ElTabPane,
  ElCard,
  ElTag,
  ElDivider,
  ElImage,
  ElButton,
  ElCollapse,
  ElCollapseItem,
  ElTooltip,
  ElScrollbar
} from 'element-plus';

const props = defineProps({
  selectedMeridian: Object,
  selectedAcupoint: Object,
});

// UI State Management
const activeTab = ref('overview');
const isImageExpanded = ref(false);
const isInfoExpanded = ref(false);
const activeCollapseItems = ref([]);
const relatedAcupointsExpanded = ref(true);

// Watch for changes in isInfoExpanded to update the collapse state
watch(isInfoExpanded, (newVal) => {
  activeCollapseItems.value = newVal ? ['1'] : [];
});

// Determine what content to show
const showType = computed(() => {
  if (props.selectedAcupoint) {
    return 'acupoint';
  } else if (props.selectedMeridian) {
    return 'meridian';
  } else {
    return 'none';
  }
});

// Reset tabs when selection changes
watch([() => props.selectedMeridian, () => props.selectedAcupoint], () => {
  activeTab.value = 'overview';
  isImageExpanded.value = false;
  isInfoExpanded.value = false;
});

// Format the text with proper line breaks and handle HTML formatting
const formatText = (text) => {
  if (!text) return '';
  
  // Handle line breaks
  let formattedText = text.replace(/\n/g, '<br>');
  
  // Handle bold text using **text** pattern
  formattedText = formattedText.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
  
  // Handle emphasis using *text* pattern
  formattedText = formattedText.replace(/\*(.*?)\*/g, '<em>$1</em>');
  
  return formattedText;
};

// Get the detail sections for acupoints
const detailSections = computed(() => {
  if (!props.selectedAcupoint || !props.selectedAcupoint.detail) return [];
  
  const detail = props.selectedAcupoint.detail;
  const sections = [];
  
  // Parse the detail text to extract sections
  const lines = detail.split('\n');
  
  for (const line of lines) {
    const match = line.match(/【(.+?)】：(.+)/);
    if (match) {
      sections.push({
        title: match[1],
        content: match[2]
      });
    }
  }
  
  return sections;
});

// Get general info for acupoint
const acupointGeneralInfo = computed(() => {
  if (!props.selectedAcupoint) return [];
  
  const info = [];
  
  if (props.selectedAcupoint.no) {
    info.push({
      label: '编号',
      value: props.selectedAcupoint.no,
      icon: '🔢'
    });
  }
  
  if (props.selectedAcupoint.meridian_name) {
    info.push({
      label: '所属经络',
      value: props.selectedAcupoint.meridian_name,
      icon: '🧠'
    });
  }
  
  if (props.selectedAcupoint.location) {
    info.push({
      label: '位置',
      value: props.selectedAcupoint.location,
      icon: '📍'
    });
  }
  
  if (props.selectedAcupoint.properties) {
    info.push({
      label: '性质',
      value: props.selectedAcupoint.properties,
      icon: '⚡'
    });
  }
  
  return info;
});

// Get functions for acupoint
const acupointFunctions = computed(() => {
  if (!props.selectedAcupoint || !props.selectedAcupoint.functions) return [];
  
  // Parse functions from string or array
  let functions = [];
  if (typeof props.selectedAcupoint.functions === 'string') {
    functions = props.selectedAcupoint.functions.split('\n').filter(f => f.trim());
  } else if (Array.isArray(props.selectedAcupoint.functions)) {
    functions = props.selectedAcupoint.functions;
  }
  
  return functions;
});

// Get clinical applications for acupoint
const acupointApplications = computed(() => {
  if (!props.selectedAcupoint || !props.selectedAcupoint.applications) return [];
  
  // Parse applications from string or array
  let applications = [];
  if (typeof props.selectedAcupoint.applications === 'string') {
    applications = props.selectedAcupoint.applications.split('\n').filter(a => a.trim());
  } else if (Array.isArray(props.selectedAcupoint.applications)) {
    applications = props.selectedAcupoint.applications;
  }
  
  return applications;
});

// Toggle expanded image view
const toggleImageView = () => {
  isImageExpanded.value = !isImageExpanded.value;
};

// Check if we have an image to display
const hasImage = computed(() => {
  if (showType.value === 'meridian') {
    return !!props.selectedMeridian?.pic;
  } else if (showType.value === 'acupoint') {
    return !!props.selectedAcupoint?.image_url;
  }
  return false;
});

// Get image url
const imageUrl = computed(() => {
  if (showType.value === 'meridian') {
    return props.selectedMeridian?.pic || '';
  } else if (showType.value === 'acupoint') {
    return props.selectedAcupoint?.image_url || '';
  }
  return '';
});

// Get meridian path count
const meridianAcupointCount = computed(() => {
  if (!props.selectedMeridian || !props.selectedMeridian.acupoint_count) {
    return '未知';
  }
  return props.selectedMeridian.acupoint_count;
});

// Get related data
const relatedAcupoints = computed(() => {
  // This would ideally be populated from the backend
  // For now, we'll use placeholder data based on the current selection
  if (showType.value === 'meridian' && props.selectedMeridian) {
    // Placeholder: In a real implementation, this would be fetched from the backend
    return []; // Would contain an array of related acupoints for this meridian
  } else if (showType.value === 'acupoint' && props.selectedAcupoint) {
    // Placeholder: In a real implementation, this would be fetched from the backend
    return []; // Would contain an array of related acupoints
  }
  return [];
});
</script>

<template>
  <div class="detail-panel">
    <!-- Empty state -->
    <div v-if="showType === 'none'" class="empty-state">
      <div class="empty-content">
        <div class="empty-icon">📋</div>
        <div class="empty-text">请从左侧选择一个经络或穴位查看详细信息</div>
      </div>
    </div>
    
    <!-- Meridian details -->
    <div v-else-if="showType === 'meridian'" class="detail-content meridian-details">
      <ElScrollbar>
        <!-- Header with title and image -->
        <div class="detail-header">
          <div class="title-section">
            <ElTag size="large" type="primary" effect="dark" class="code-tag">{{ selectedMeridian.no }}</ElTag>
            <h2 class="title">{{ selectedMeridian.name }}</h2>
          </div>
          
          <div v-if="hasImage" :class="['image-container', { expanded: isImageExpanded }]">
            <ElImage
              :src="imageUrl"
              fit="contain"
              :preview-src-list="[imageUrl]"
              :initial-index="0"
              alt="经络图"
              class="detail-image"
            >
              <template #error>
                <div class="image-error">
                  <i class="el-icon-picture"></i>
                  <div>加载图片失败</div>
                </div>
              </template>
            </ElImage>
            
            <div class="image-actions">
              <ElButton
                size="small"
                @click="toggleImageView"
                :icon="isImageExpanded ? 'ZoomOut' : 'ZoomIn'"
              >
                {{ isImageExpanded ? '收起' : '放大' }}
              </ElButton>
            </div>
          </div>
        </div>
        
        <ElDivider />
        
        <!-- Tabs for different content -->
        <ElTabs v-model="activeTab" type="border-card" class="detail-tabs">
          <ElTabPane label="概述" name="overview">
            <div class="info-grid">
              <div class="info-card">
                <div class="info-icon">🔢</div>
                <div class="info-label">经络编号</div>
                <div class="info-value">{{ selectedMeridian.no }}</div>
              </div>
              
              <div class="info-card">
                <div class="info-icon">📊</div>
                <div class="info-label">穴位数量</div>
                <div class="info-value">{{ meridianAcupointCount }}</div>
              </div>
              
              <div class="info-card" v-if="selectedMeridian.element">
                <div class="info-icon">🌍</div>
                <div class="info-label">五行属性</div>
                <div class="info-value">{{ selectedMeridian.element }}</div>
              </div>
              
              <div class="info-card" v-if="selectedMeridian.yin_yang">
                <div class="info-icon">☯️</div>
                <div class="info-label">阴阳属性</div>
                <div class="info-value">{{ selectedMeridian.yin_yang }}</div>
              </div>
            </div>
            
            <div v-if="selectedMeridian.introduction" class="intro-section">
              <h3 class="section-title">经络简介</h3>
              <div class="intro-content" v-html="formatText(selectedMeridian.introduction)"></div>
            </div>
            
            <div v-if="selectedMeridian.path_description" class="path-section">
              <h3 class="section-title">经络循行</h3>
              <div class="path-content" v-html="formatText(selectedMeridian.path_description)"></div>
            </div>
          </ElTabPane>
          
          <ElTabPane label="功能特点" name="functions" v-if="selectedMeridian.functions">
            <div class="functions-section">
              <div class="function-item" v-for="(func, index) in selectedMeridian.functions" :key="index">
                <div class="function-number">{{ index + 1 }}</div>
                <div class="function-text">{{ func }}</div>
              </div>
            </div>
          </ElTabPane>
          
          <ElTabPane label="相关经络" name="related" v-if="selectedMeridian.related_meridians">
            <div class="related-section">
              <div v-for="(related, index) in selectedMeridian.related_meridians" :key="index" class="related-item">
                <ElTag size="medium" effect="plain">{{ related.name }}</ElTag>
                <div class="related-description">{{ related.relationship }}</div>
              </div>
            </div>
          </ElTabPane>
        </ElTabs>
        
        <!-- References and links -->
        <div class="references-section">
          <ElDivider>更多资料</ElDivider>
          <div class="reference-links">
            <ElButton
              v-if="selectedMeridian.link"
              type="primary"
              plain
              size="small"
              @click="window.open(selectedMeridian.link, '_blank')"
              icon="Link"
            >
              详细参考资料
            </ElButton>
          </div>
        </div>
      </ElScrollbar>
    </div>
    
    <!-- Acupoint details -->
    <div v-else-if="showType === 'acupoint'" class="detail-content acupoint-details">
      <ElScrollbar>
        <!-- Header with title and image -->
        <div class="detail-header">
          <div class="title-section">
            <div class="title-tags">
              <ElTag size="medium" type="success" effect="dark" class="code-tag">{{ selectedAcupoint.no }}</ElTag>
              <ElTag size="medium" type="info" effect="plain">{{ selectedAcupoint.meridian_name }}</ElTag>
            </div>
            <h2 class="title">{{ selectedAcupoint.name }}</h2>
          </div>
          
          <div v-if="hasImage" :class="['image-container', { expanded: isImageExpanded }]">
            <ElImage
              :src="imageUrl"
              fit="contain"
              :preview-src-list="[imageUrl]"
              :initial-index="0"
              alt="穴位图"
              class="detail-image"
            >
              <template #error>
                <div class="image-error">
                  <i class="el-icon-picture"></i>
                  <div>加载图片失败</div>
                </div>
              </template>
            </ElImage>
            
            <div class="image-actions">
              <ElButton
                size="small"
                @click="toggleImageView"
                :icon="isImageExpanded ? 'ZoomOut' : 'ZoomIn'"
              >
                {{ isImageExpanded ? '收起' : '放大' }}
              </ElButton>
            </div>
          </div>
        </div>
        
        <ElDivider />
        
        <!-- Tabs for different content -->
        <ElTabs v-model="activeTab" type="border-card" class="detail-tabs">
          <ElTabPane label="概述" name="overview">
            <!-- Basic information cards -->
            <div class="info-grid">
              <div class="info-card" v-for="(info, index) in acupointGeneralInfo" :key="index">
                <div class="info-icon">{{ info.icon }}</div>
                <div class="info-label">{{ info.label }}</div>
                <div class="info-value">{{ info.value }}</div>
              </div>
            </div>
            
            <!-- Location section with expanded details -->
            <div v-if="selectedAcupoint.location" class="location-section">
              <h3 class="section-title">
                <span>精确定位</span>
                <ElButton
                  type="text"
                  size="small"
                  @click="isInfoExpanded = !isInfoExpanded"
                  :icon="isInfoExpanded ? 'ArrowUp' : 'ArrowDown'"
                >
                  {{ isInfoExpanded ? '收起' : '详细' }}
                </ElButton>
              </h3>
              
              <div class="location-basic">{{ selectedAcupoint.location }}</div>
              
              <ElCollapse v-model="activeCollapseItems">
                <ElCollapseItem name="1">
                  <div class="location-details" v-if="selectedAcupoint.location_detail" v-html="formatText(selectedAcupoint.location_detail)"></div>
                  <div class="location-tips" v-if="selectedAcupoint.location_tips">
                    <div class="tip-title">取穴要点</div>
                    <div class="tip-content" v-html="formatText(selectedAcupoint.location_tips)"></div>
                  </div>
                </ElCollapseItem>
              </ElCollapse>
            </div>
            
            <!-- Function & application highlights -->
            <div class="highlight-section">
              <div v-if="acupointFunctions.length > 0" class="highlight-functions">
                <h3 class="section-title">主要功效</h3>
                <div class="function-list">
                  <div v-for="(func, index) in acupointFunctions.slice(0, 3)" :key="index" class="highlight-item">
                    <div class="highlight-icon">⚡</div>
                    <div class="highlight-text">{{ func }}</div>
                  </div>
                </div>
              </div>
              
              <div v-if="acupointApplications.length > 0" class="highlight-applications">
                <h3 class="section-title">应用范围</h3>
                <div class="application-tags">
                  <ElTag
                    v-for="(app, index) in acupointApplications.slice(0, 5)"
                    :key="index"
                    size="small"
                    effect="light"
                    class="application-tag"
                  >
                    {{ app }}
                  </ElTag>
                </div>
              </div>
            </div>
          </ElTabPane>
          
          <ElTabPane label="功能应用" name="functions" v-if="acupointFunctions.length > 0 || acupointApplications.length > 0">
            <div v-if="acupointFunctions.length > 0" class="functions-section">
              <h3 class="section-title">功效作用</h3>
              <div class="function-item" v-for="(func, index) in acupointFunctions" :key="index">
                <div class="function-number">{{ index + 1 }}</div>
                <div class="function-text">{{ func }}</div>
              </div>
            </div>
            
            <ElDivider v-if="acupointFunctions.length > 0 && acupointApplications.length > 0"></ElDivider>
            
            <div v-if="acupointApplications.length > 0" class="applications-section">
              <h3 class="section-title">临床应用</h3>
              <div class="application-item" v-for="(app, index) in acupointApplications" :key="index">
                <div class="application-number">{{ index + 1 }}</div>
                <div class="application-text">{{ app }}</div>
              </div>
            </div>
          </ElTabPane>
          
          <ElTabPane label="详细说明" name="details" v-if="detailSections.length > 0 || selectedAcupoint.description">
            <div v-if="detailSections.length > 0" class="sections-list">
              <div v-for="(section, index) in detailSections" :key="index" class="info-section">
                <h3 class="section-title">{{ section.title }}</h3>
                <div class="section-content" v-html="formatText(section.content)"></div>
              </div>
            </div>
            
            <div v-if="selectedAcupoint.description" class="description-section">
              <h3 class="section-title">详细说明</h3>
              <div class="description-content" v-html="formatText(selectedAcupoint.description)"></div>
            </div>
          </ElTabPane>
          
          <ElTabPane label="穴位配伍" name="combinations" v-if="selectedAcupoint.combinations">
            <div class="combinations-section">
              <ElCard v-for="(combo, index) in selectedAcupoint.combinations" :key="index" class="combo-card">
                <template #header>
                  <div class="combo-header">
                    <div class="combo-title">配伍方案 {{ index + 1 }}</div>
                    <ElTag size="small" type="warning">{{ combo.purpose }}</ElTag>
                  </div>
                </template>
                <div class="combo-points">
                  <ElTag
                    v-for="(point, pidx) in combo.points"
                    :key="pidx"
                    class="combo-point"
                    size="medium"
                    effect="plain"
                  >
                    {{ point }}
                  </ElTag>
                </div>
                <div class="combo-description">{{ combo.description }}</div>
              </ElCard>
            </div>
          </ElTabPane>
        </ElTabs>
        
        <!-- References and links -->
        <div class="references-section">
          <ElDivider>更多资料</ElDivider>
          <div class="reference-links">
            <ElButton
              v-if="selectedAcupoint.link"
              type="primary"
              plain
              size="small"
              @click="window.open(selectedAcupoint.link, '_blank')"
              icon="Link"
            >
              详细参考资料
            </ElButton>
            
            <ElButton
              v-if="selectedAcupoint.video_url"
              type="success"
              plain
              size="small"
              @click="window.open(selectedAcupoint.video_url, '_blank')"
              icon="VideoPlay"
            >
              视频教学
            </ElButton>
          </div>
        </div>
      </ElScrollbar>
    </div>
  </div>
</template>

<style scoped>
.detail-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: white;
  height: 35%;
  border-top: 1px solid #ebeef5;
  position: relative;
  overflow: hidden;
}

.detail-content {
  flex: 1;
  overflow: hidden;
}

/* Empty state */
.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f8f8f8;
}

.empty-content {
  text-align: center;
  color: #909399;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-text {
  font-size: 16px;
  color: #606266;
}

/* Header styling */
.detail-header {
  display: flex;
  justify-content: space-between;
  padding: 16px 20px 0;
  align-items: flex-start;
  position: relative;
}

.title-section {
  flex: 1;
  min-width: 0;
}

.title-tags {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.title {
  font-size: 22px;
  font-weight: 600;
  margin: 0;
  color: #303133;
  line-height: 1.3;
}

.code-tag {
  font-family: monospace;
  font-weight: bold;
}

/* Image styling */
.image-container {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  margin-left: 16px;
  flex-shrink: 0;
  position: relative;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
}

.image-container.expanded {
  width: 200px;
  height: 200px;
}

.detail-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.image-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  padding: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.image-container:hover .image-actions {
  opacity: 1;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 12px;
  color: #909399;
}

.image-error i {
  font-size: 32px;
  margin-bottom: 8px;
}

/* Tabs styling */
.detail-tabs {
  margin: 0 12px;
}

/* Info grid */
.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.info-card {
  background-color: #f8f8f8;
  border-radius: 8px;
  padding: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.info-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.info-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.info-value {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

/* Sections */
.section-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 12px;
  color: #303133;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.intro-section,
.path-section,
.location-section,
.highlight-section,
.functions-section,
.applications-section,
.description-section,
.info-section,
.combinations-section {
  margin-bottom: 24px;
}

.intro-content,
.path-content,
.section-content,
.description-content {
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
}

/* Location section */
.location-basic {
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
  margin-bottom: 8px;
}

.location-details,
.location-tips {
  font-size: 13px;
  line-height: 1.6;
  color: #606266;
  background-color: #f8f8f8;
  padding: 12px;
  border-radius: 4px;
  margin-top: 12px;
}

.tip-title {
  font-weight: 600;
  margin-bottom: 8px;
  color: #409eff;
}

/* Function and application highlights */
.highlight-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.function-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.highlight-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
}

.highlight-icon {
  font-size: 18px;
}

.highlight-text {
  font-size: 14px;
  color: #606266;
}

.application-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.application-tag {
  margin-right: 0 !important;
}

/* Functions and applications lists */
.function-item,
.application-item {
  display: flex;
  margin-bottom: 12px;
  align-items: flex-start;
}

.function-number,
.application-number {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  margin-right: 12px;
  flex-shrink: 0;
}

.application-number {
  background-color: #67c23a;
}

.function-text,
.application-text {
  flex: 1;
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
  padding-top: 2px;
}

/* Combinations */
.combinations-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.combo-card {
  margin-bottom: 0 !important;
}

.combo-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.combo-title {
  font-weight: 600;
  font-size: 14px;
}

.combo-points {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
}

.combo-point {
  margin-right: 0 !important;
}

.combo-description {
  font-size: 13px;
  color: #606266;
  line-height: 1.5;
}

/* References */
.references-section {
  padding: 0 20px 20px;
}

.reference-links {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 8px 0;
}

/* Icons */
.el-icon-picture:before {
  content: "🖼️";
}

/* Media queries */
@media (max-width: 768px) {
  .image-container {
    width: 80px;
    height: 80px;
  }
  
  .image-container.expanded {
    width: 150px;
    height: 150px;
  }
  
  .info-grid {
    grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
  }
}
</style>